package backingBean;

import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import model.User;
import abstractFactory.Factory;
import dao.User.UserDAO;

public class BeanUser {
	private User user = new User();
	private List<User> users;
	private boolean logged = false;
	
	public BeanUser(){}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public boolean getLogged() {
		return logged;
	}

	public void setLogged(boolean logged) {
		this.logged = logged;
	}
	
	public void register(){
		UserDAO userDao = Factory.getInstance("JPA").createUserDAO();
		if(userDao.save(user)){
			FacesMessage msg = new FacesMessage("Cadastrado com Sucesso.");
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage("gravar", msg);
			user = new User();
		}	
		else{
			user = new User();
			FacesMessage msg = new FacesMessage("Tente outra vez.");
			FacesContext fc = FacesContext.getCurrentInstance();
			fc.addMessage("gravar", msg);
		}
	}

	public List<User> getUsers(){
		UserDAO userDao = Factory.getInstance("JPA").createUserDAO();
		users = userDao.getAllUsers(); 
		return users;
	}

	public User editUser(){
		return user;
	}

	public void delete(){
		UserDAO userDao = Factory.getInstance("JPA").createUserDAO();
		user.setActive(0);
		userDao.update(user);
		user = new User();
	}

	public String logar(){
		UserDAO userDao = Factory.getInstance("JPA").createUserDAO();
		User u = userDao.doLogin(user.getLogin(), user.getPassword());
		if(u != null){
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			session.setAttribute("usuario", u);
			this.setLogged(true);
			return "login";
		}
		else
			return "erro";
	}
	public String logoff(){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.invalidate();
		this.setLogged(false);
		user = new User();
		return "logoff";
	}
}